package org.phoenixframework.oauth2.server.config.security;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import lombok.AllArgsConstructor;
import org.phoenixframework.common.entity.SysResource;
import org.phoenixframework.common.entity.SysRole;
import org.phoenixframework.common.entity.SysRoleResource;
import org.phoenixframework.oauth2.server.config.redis.service.IRedisService;
import org.phoenixframework.oauth2.server.constant.AuthConstant;
import org.phoenixframework.oauth2.server.service.ISysResourceService;
import org.phoenixframework.oauth2.server.service.ISysRoleResourceService;
import org.phoenixframework.oauth2.server.service.ISysRoleService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/6/7 17:06
 * Description:
 */
@AllArgsConstructor
@Component
public class ResourceServiceImpl {

    private final ISysResourceService sysResourceService;

    private final ISysRoleService sysRoleService;

    private final ISysRoleResourceService sysRoleResourceService;

    private final IRedisService redisService;

    @PostConstruct
    public void initRoleResource() {
        // 获取所有的角色
        List<SysRole> sysRoles = sysRoleService.list();
        // 获取所有可访问的后台资源
        List<SysResource> sysResources = sysResourceService.list().stream().distinct().collect(Collectors.toList());
        // 角色和资源对应关系
        List<SysRoleResource> sysRoleResources = sysRoleResourceService.list();

        Map<String, List<String>> roleResourceMap = new TreeMap<>();
        sysResources.forEach(sysResource -> {
            // 每个资源对应的角色Id集合
            List<Long> roleIds = sysRoleResources.stream()
                    .filter(sysRoleResource -> sysRoleResource.getResourceId().equals(sysResource.getId()))
                    .map(SysRoleResource::getRoleId)
                    .collect(Collectors.toList());
            // 每个资源对应的角色Code集合
            List<String> roleCodes = sysRoles.stream()
                    .filter(sysRole -> roleIds.contains(sysRole.getId()))
                    .map(sysRole -> sysRole.getId() + "_" + sysRole.getCode())
                    .collect(Collectors.toList());
            roleResourceMap.put(sysResource.getUrl(), roleCodes);
        });
        redisService.del(AuthConstant.RESOURCE_ROLES_MAP);
        if (MapUtil.isNotEmpty(roleResourceMap)) {
            redisService.hSetAll(AuthConstant.RESOURCE_ROLES_MAP, roleResourceMap);
        }

    }

}
